/*
 * drive.c
 *
 *  Created on: 2012.12.02.
 *      Author: Peter
 */
#include "stm32f4xx.h"
#include "drive.h"



void InitDrivePeriphs(void)
{
	  TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
	  TIM_OCInitTypeDef TIM_OCInitStructure;
	  GPIO_InitTypeDef GPIO_InitStructure;

	  TIM_TimeBaseStructInit(&TIM_OCInitStructure);
	  TIM_OCStructInit(&TIM_OCInitStructure);
	  GPIO_StructInit(&GPIO_InitStructure);
	  /* Initialize TIM8 */
	  /* TIM8 clock enable */
	  RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM8, ENABLE);
	  /* GPIOC clocks enable */
	  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);

	  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
	  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
	  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ;
	  GPIO_Init(GPIOC, &GPIO_InitStructure);

	  /* Connect TIM8 pins to AF2 */
	  GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_TIM8);

	  /* Time base configuration */
	  TIM_TimeBaseStructure.TIM_Period = PWM_PERIOD_DRIVE;
	  TIM_TimeBaseStructure.TIM_Prescaler = PWM_DRIVE_PRESC;
	  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
	  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

	  TIM_TimeBaseInit(TIM8, &TIM_TimeBaseStructure);

	  /* PWM1 Mode configuration: Channel1 */
	  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
	  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	  TIM_OCInitStructure.TIM_Pulse = PWM_DRIVE_CCR1;
	  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

	  TIM_OC1Init(TIM8, &TIM_OCInitStructure);

	  TIM_OC1PreloadConfig(TIM8, TIM_OCPreload_Enable);
	  /* Enable TIM8 Preload register on ARR */
	  TIM_ARRPreloadConfig(TIM8, ENABLE);
	  /* TIM8 enable counter */
	  TIM_Cmd(TIM8, ENABLE);
	  /* TIM8 Main Output Enable */
	  TIM_CtrlPWMOutputs(TIM8, ENABLE);
}

void SetDrivePWM(int16_t speed)
{
	uint16_t pwm = -speed + PWM_DRIVE_CCR1;
	TIM8->CCR1 = pwm;
}
